package com.chushouya.manager.service.api.impl;


import com.chushouya.common.support.Contexts;
import com.chushouya.manager.dao.entity.UserExtendEntity;
import com.chushouya.manager.dao.repository.UserExtendRepository;
import com.chushouya.manager.dto.admin.user.UserInfoUpdateDTO;
import com.chushouya.manager.service.api.UserExtendService;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Validate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@Service
public class UserExtendServiceImpl implements UserExtendService {
    @Resource
    private UserExtendRepository userExtendRepository;

    @Override
    public void updateUserInfo(UserInfoUpdateDTO dto) {
        UserExtendEntity userExtend = userExtendRepository.selectByAppIdAndUserId(Contexts.getHeaderContext().getAppId(),Contexts.getUserContext().getUserId());
        Validate.isNull(userExtend, "用户不存在");
        UserExtendEntity update = new UserExtendEntity();
        update.setUserExtendId(userExtend.getUserExtendId());
        update.setNickName(dto.getNickName());
        update.setAvatar(dto.getAvatar());
        update.setUpdateTime(Dates.getTimeNow());
        userExtendRepository.updateByPrimaryKeySelective(update);
    }

    @Override
    public UserExtendEntity selectByAppIdAndUserId(String appId, Long userId) {
        return userExtendRepository.selectByAppIdAndUserId(appId, userId);
    }

    @Override
    public void saveUserExtend(Long userId, String appId, String openId, String platform) {
        UserExtendEntity userExtend = userExtendRepository.selectByAppIdAndUserId(appId, userId);
        if (Objects.isNull(userExtend)) {
            UserExtendEntity insert = new UserExtendEntity();
            insert.setUserId(userId);
            insert.setAppId(appId);
            insert.setOpenId(openId);
            insert.setPlatform(platform);
            insert.setCreateTime(new Date());
            insert.setUpdateTime(new Date());
            userExtendRepository.insertSelective(insert);
        } else {
            UserExtendEntity update = new UserExtendEntity();
            update.setUserExtendId(userExtend.getUserExtendId());
            update.setPlatform(platform);
            update.setOpenId(openId);
            update.setUpdateTime(Dates.getTimeNow());
            userExtendRepository.updateByPrimaryKeySelective(update);
        }
    }

}
